/// <license>
/// Copyright (c) 2002-2008, DotNetNuke Corporation
/// All rights reserved
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
/// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
/// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
/// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
/// of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
/// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
/// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
/// DEALINGS IN THE SOFTWARE.
/// </license>

using System;
using System.Collections.Generic;
using System.Web.UI;

using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.UI.WebControls;
using DNNLocalization = DotNetNuke.Services.Localization.Localization;
using DotNetNuke.Entities.Users;
using DotNetNuke.Common;
using DotNetNuke.Entities.Portals;


namespace DotNetNuke.ModuleToolkit.Controls
{
    /// <summary>
    /// An Edit Control to edit Users
    /// </summary>
    /// <history>
    [ToolboxData("<{0}:UserEditControl runat=server></{0}:UserEditControl>")]
    public class UserEditControl : IntegerEditControl, IPostBackEventHandler
    {

        private int portalID = Null.NullInteger;
        private string userNameLookup = Null.NullString;
        private string nameSuffix = ":Name";

        #region Protected Properties

        protected string DisplayName
        {
            get
            {
                string displayname = Null.NullString;
                if (User != null)
                {
                    displayname = User.DisplayName;
                }
                return displayname;
            }
        }

        protected UserInfo User
        {
            get 
            {
                UserInfo user = null;
                if (UserID != Null.NullInteger)
                {
                    user = UserController.GetUser(PortalID, UserID, false);
                }
                return user; 
            }
        }

        protected string UserName
        {
            get
            {
                string username = Null.NullString;
                if (User != null)
                {
                    username = User.Username;
                }
                return username;
            }
        }

        protected int OldUserID
        {
            get { return OldIntegerValue; }
        }

        protected int UserID
        {
            get 
            {
                return IntegerValue;
            }
        }


        #endregion

        #region Public Properties

        public int PortalID
        {
            get { return portalID; }
            set { portalID = value; }
        }

        #endregion

        private void RenderGetUserButton(HtmlTextWriter writer)
        {
            string buttonText = DNNLocalization.GetString("GetUser", this.LocalResourceFile);

            writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, "GetUser"));
            writer.AddAttribute(HtmlTextWriterAttribute.Title, buttonText);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "CommandButton");
            writer.RenderBeginTag(HtmlTextWriterTag.A);

            //Render Image
            writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveClientUrl("~/images/view.gif"));
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
            writer.RenderBeginTag(HtmlTextWriterTag.Img);

            //Render end of Image
            writer.RenderEndTag();

            //Render a spacer
            writer.Write("&nbsp;");

            //Render Hyperlink Text
            writer.Write(buttonText);

            //Render end of Hyperlink
            writer.RenderEndTag();
        }

        #region Protected Methods

        protected override void OnDataChanged(EventArgs e)
        {
            PropertyEditorEventArgs args = new PropertyEditorEventArgs(Name);
            args.Value = UserID;
            args.OldValue = OldUserID;
            args.StringValue = StringValue;
            base.OnValueChanged(args);
        }

        /// <summary>
        /// Render renders the control in edit mode
        /// </summary>
        /// <param name="writer">An HtmlTextWriter</param>
        protected override void RenderEditMode(System.Web.UI.HtmlTextWriter writer)
        {
            //Render the Span Tag
            ControlStyle.AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Span);

            //Render the Hidden Tag
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID);
            writer.AddAttribute(HtmlTextWriterAttribute.Value, UserID.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "hidden");
            writer.RenderBeginTag(HtmlTextWriterTag.Input);

            //Render the Input Tag
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + nameSuffix);
            writer.AddAttribute(HtmlTextWriterAttribute.Value, UserName);
            writer.RenderBeginTag(HtmlTextWriterTag.Input);

            //Close Input Tag
            writer.RenderEndTag();

            //Render a spacer
            writer.Write("&nbsp;&nbsp;");

            //Render the GetUser Button
            RenderGetUserButton(writer);

            writer.WriteBreak();

            //Render DisplayName
            writer.Write(DisplayName);

            //Close Span Tag
            writer.RenderEndTag();
        }

        /// <summary>
        /// RenderViewMode renders the control in view mode
        /// </summary>
        /// <param name="writer">An HtmlTextWriter</param>
        protected override void RenderViewMode(System.Web.UI.HtmlTextWriter writer)
        {
            ControlStyle.AddAttributesToRender(writer);
            writer.RenderBeginTag(HtmlTextWriterTag.Span);
            writer.Write(UserName);
            writer.RenderEndTag();
        }

        #endregion

        public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            //Check if a Name has been posted back that is different from the current username
            string value = postCollection[postDataKey + nameSuffix];

            if (!String.IsNullOrEmpty(value) && value != UserName)
                userNameLookup = value;

            return base.LoadPostData(postDataKey, postCollection);
        }


        #region IPostBackEventHandler Members

        public void RaisePostBackEvent(string eventArgument)
        {
            if (eventArgument == "GetUser" && !string.IsNullOrEmpty(userNameLookup))
            {
                //Get new User
                UserInfo user = UserController.GetUserByName(PortalID, userNameLookup);
                if (user != null)
                    Value = user.UserID;
            }
        }

        #endregion

    }

}
